/*
    Geocache: some utilities for managing and visualizing geocache information
    Copyright (C) 2008  Gary Jackson

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/*
 * GpxToPointSet.java
 */

package com.thegbomb.geocache;

import com.thegbomb.common.Mapper;
import com.thegbomb.common.SingleIterator;
import com.thegbomb.sphere.PropertiesPointSet;
import java.io.BufferedReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import org.xml.sax.InputSource;

/**
 *
 * @author Gary Jackson
 */
public class GpxToPointSet implements Mapper<Reader, PropertiesPointSet> {
    public Iterator<PropertiesPointSet> map(Reader input) {
        if (! (input instanceof BufferedReader))
            input = new BufferedReader(input);
        
        // Parse the input file and extract the waypoints in to a PointSet
        GpxPointExtractor extractor = new GpxPointExtractor();
        SAXResult result = new SAXResult(extractor);
        SAXSource source = new SAXSource(new InputSource(input));
        
        try {
            Transformer tran = SAXTransformerFactory.newInstance().newTransformer();
            
            tran.transform(source, result);
        } catch (TransformerException e) {
            throw new RuntimeException(e);
        }
        
        Map<String, Object> props = new HashMap<String, Object>();
        props.put("name", extractor.getName());
        PropertiesPointSet ps = new PropertiesPointSet(extractor.getPoints(), props);
        
        return new SingleIterator<PropertiesPointSet>(ps);
    }
}
